package com.atguigu.juc.day04.pool;

import java.util.concurrent.*;

public class Demo01MyPool {

    public static void main(String[] args) {

        ExecutorService executorService = getExecutorService();

        // 3、给线程池分配任务
        try {
            while (true) {
                TimeUnit.MILLISECONDS.sleep(100);

                executorService.submit(()->{
                    try {
                        for (int i = 0; i < Math.random() * 10; i++) {
                            TimeUnit.SECONDS.sleep(1);
                            System.out.println(Thread.currentThread().getName() + " is working.");
                        }
                        System.out.println(Thread.currentThread().getName() + " task finish.");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                });

            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


    }

    public static ExecutorService getExecutorService() {
        // 1、准备七个参数
        // [1]核心线程数
        int corePoolSize = 3;

        // [2]最大线程数
        int maximumPoolSize = 5;

        // [3]非核心线程最大空闲时间数量
        long keepAliveTime = 10;

        // [4]非核心线程最大空闲时间单位
        TimeUnit unit = TimeUnit.SECONDS;

        // [5]等待队列的长度
        int workQueueLen = 10;

        // [6]等待队列
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(workQueueLen);

        // [7]线程工厂
        ThreadFactory threadFactory = Executors.defaultThreadFactory();

        // [8]拒绝策略
        RejectedExecutionHandler handler =
                // new ThreadPoolExecutor.CallerRunsPolicy();
                // new ThreadPoolExecutor.AbortPolicy();
                new ThreadPoolExecutor.DiscardOldestPolicy();

        // 2、创建线程池对象
        ExecutorService executorService = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler);

        return executorService;
    }

}
